package servlets;

import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.DBHelper;

/**
 * Servlet implementation class CheckUserRegisted
 */
@WebServlet("/CheckUserRegisted")
public class CheckUserRegisted extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckUserRegisted() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void check(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException{
    	try {
    		PrintWriter out = response.getWriter();
    		Connection con = DBHelper.getConnection();
    		PreparedStatement sql = DBHelper.getprepareStatement(con,"select * from JOBLOGIN");
    		ResultSet rs = sql.executeQuery();
    		ArrayList<String> list = new ArrayList<String>(); 
    		while (rs.next()) { 
    			list.add(rs.getString("USERNAME"));
    		}
    		if (list != null && list.size() > 0) {
    			String[] userList= new String[list.size()];
    			for (int i = 0; i < list.size(); i++) {
    				userList[i] = list.get(i);
    			}
    			String user=new String(request.getParameter("user").getBytes("ISO-8859-1"),"GB18030");	
    			Arrays.sort(userList);									
    			int result=Arrays.binarySearch(userList,user);			
    			if(result>-1){
    				out.println("9");
    			}
    		}
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			check(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			check(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
